package com.xiaow.common.interceptor;

import com.xiaow.entity.UserEntity;
import com.xiaow.mapper.UserMapper;
import com.xiaow.utils.JwtUtils;
import com.xiaow.utils.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JWTAuthorizationFilter extends BasicAuthenticationFilter {


    public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {

        String tokenHeader = request.getHeader("token");
        // 如果请求头中有token，则进行解析，并且设置认证信息
        SecurityContextHolder.getContext().setAuthentication(getAuthentication(tokenHeader));
        super.doFilterInternal(request, response, chain);
    }

    // 这里从token中获取用户信息并新建一个token
    private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader) {
        UserMapper userMapper = SpringUtils.getBean(UserMapper.class);
        String usernameWithoutSecert = JwtUtils.getUsernameWithoutSecert(tokenHeader);
        //目的是为了获取最新的salt
        UserEntity byUsername1 = userMapper.findByUsername(usernameWithoutSecert);
        System.out.println(byUsername1.getSalt());
        String username = JwtUtils.getUsername(tokenHeader,byUsername1.getSalt());
        if (username != null) {
//            在数据库中取出最新的salt值，如果未进行注销，salt值和最初登录时的salt为相同的
            List<SimpleGrantedAuthority> userRoles = JwtUtils.getUserRole(tokenHeader,byUsername1.getSalt());
            return new UsernamePasswordAuthenticationToken(username, null, userRoles);
        }
        return null;
    }
}
